const fp = require('loadsh/fp');

// 数据
// horsepower 马力， dollar_value 价格， in_stock 库存

const cars = [
    {
        name: 'Ferrari FF',
        horsepower: 660,
        dollar_value: 700000,
        in_stock: true
    },
    {
        name: 'Spyker C12 Zagato',
        horsepower: 650,
        dollar_value: 648000,
        in_stock: false
    },
    {
        name: 'Jaguar XKR-S',
        horsepower: 550,
        dollar_value: 132000,
        in_stock: false
    },
    {
        name: 'Audi R8',
        horsepower: 525,
        dollar_value: 1142000,
        in_stock: false
    },
    {
        name: 'Aston Martin One-77',
        horsepower: 750,
        dollar_value: 1850000,
        in_stock: true
    },
    {
        name: 'Pagani Huayra',
        horsepower: 700,
        dollar_value: 130000,
        in_stock: false
    }
]


// 练习 1：使用函数组合重新实现下这个函数
// original code
// let isLastInStock = function (cars) {
//     let last_car = fp.last(cars);
//     return fp.prop('in_stock', last_car);
// }

let isLastInStock = fp.flowRight(fp.prop('in_stock'), fp.last);

console.log('isLastInStock', isLastInStock(cars));


// 练习 2：使用fp获取第一个car的name
let firstCarName = fp.flowRight(fp.prop('name'), fp.first);

console.log('firstCarName', firstCarName(cars));


// 练习 3：使用帮助函数_average、fp求平均价格
let _average = function (xs) {
    return fp.reduce(fp.add, 0, xs) / xs.length;
};

let averageDollarValue = fp.flowRight(_average, fp.map(fp.prop('dollar_value')));

console.log('averageDollarValue', averageDollarValue(cars));


// 练习 4：使用fp写一个sanitizeNames函数，返回一个下划线连接的小写字符串，把数组中的name换成这种形式
let _underscore = fp.replace(/\W+/g, '_');

let sanitizeNames = fp.flowRight(fp.map(_underscore), fp.map(fp.toLower), fp.map(fp.prop('name')));

console.log('sanitizeNames', sanitizeNames(cars));
